package www.test.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;



import www.test.bean.ShipInfo;
import www.test.servlet.InfoServlet;
import www.test.utils.BeanListHandler;
import www.test.utils.KeyId;
import www.test.utils.PageUtils;
import www.test.utils.jdbcUtils;

public class ShipDao
{

	

	public static List<HashMap<String, ?>> getShipInfoList(HttpServletRequest request, HttpServletResponse response, ShipInfo domain) throws SQLException
	{
		String sortparam="";
		String searchParam ="";
		if(domain.getSearchName()!=null&&!("".equals(domain.getSearchName())))
		{
			searchParam+="SHIPNAME like '%"+domain.getSearchName()+"%'  and";
			
		}
		
		if(domain.getSearchVoyage()!=null&&!("".equals(domain.getSearchVoyage())))
		{
			searchParam+=" voyage like '%"+domain.getSearchVoyage()+"%'  and";
			
		} 
		
		
		if(domain.getSearchCategory()!=null&&!("".equals(domain.getSearchCategory())))
		{
			searchParam+=" CATEGORY like  '%"+domain.getSearchCategory()+"%' and";
			
		}
		
		
		if(!"".equals(searchParam))
		{
			searchParam =" where "+searchParam.substring(0,searchParam.length()-3);
		}
		
		if((domain.getSort()!=null) &&!("".equals(domain.getSort())))
		{
			sortparam ="order by "+domain.getSort()+" "+ domain.getType();
			
		}
		
		
		String sql ="select * from info "+searchParam+sortparam;
		Object[] params={};
		
		return jdbcUtils.select(sql, params,domain.getPageSize(),domain.getCurrentPage());
	}

	public static boolean doSave(HttpServletRequest request, HttpServletResponse response, ShipInfo domain) throws SQLException
	{
		if("".equals(domain.getId()))
		{
			//id为空 新增
			
			String sql="insert into info (ID,SHIPNAME,voyage,CATEGORY)VALUES(?,?,?,?)";
			Object[] params ={KeyId.getKeyId(),domain.getShipName(),domain.getVoyage(),domain.getCategory()};
			return jdbcUtils.update(sql, params);
		}
		else
		{
			String sql="update info set shipname=? , voyage=? ,category =? where id=?";
			Object[] params={domain.getShipName(),domain.getVoyage(),domain.getCategory(),domain.getId()};
			return jdbcUtils.update(sql, params);
			
		}
	}

	public static HashMap<String, ?> getShipById(HttpServletRequest request, HttpServletResponse response, ShipInfo domain) throws SQLException
	{
		String sql ="select * from info where id=?";
		Object[] params ={domain.getId()};
		return  jdbcUtils.select(sql, params).get(0);
	}

	public static boolean delete(HttpServletRequest request, HttpServletResponse response, ShipInfo domain) throws SQLException
	{
		String sql = "delete from info where id =?";
		Object[] params ={domain.getId()};
		return jdbcUtils.update(sql, params);
	}

}
